package com.spider.http;

import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

public class HttpClient {
    public static void main(String[] args) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //创建请求Get实例
        HttpGet httpGet = new HttpGet("https://h5.ele.me/hongbao/#hardware_id=&is_lucky_group=True&lucky_number=5&track_id=&platform=4&sn=29ef424ec3af0418&theme_id=2377&device_id=&refer_user_id=115092954");

        //设置头部信息进行模拟登录（添加登录后的Cookie）
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        //httpGet.setHeader("Cookie", ".......");
        httpGet.setHeader("User-Agent", "https://h5.ele.me/hongbao/#hardware_id=&is_lucky_group=True&lucky_number=5&track_id=&platform=4&sn=29ef424ec3af0418&theme_id=2377&device_id=&refer_user_id=115092954");

        try {
            //客户端执行httpGet方法，返回响应
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);

            System.out.println(closeableHttpResponse.getStatusLine().getStatusCode());
            //得到服务响应状态码
            if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                //打印所有响应头
                Header[] headers = closeableHttpResponse.getAllHeaders();
                for (Header header : headers) {
                    System.out.println(header.getName() + ": " + header.getValue());
                }
            }
            else {
                //如果是其他状态码则做其他处理
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
